package com.example.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.system.domain.entity.Image;
import com.example.system.domain.entity.User;
import com.example.system.mapper.ImageMapper;
import com.example.system.mapper.UserMapper;
import com.example.system.service.ImageService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Objects;

@Service
public class ImageServiceImpl implements ImageService {
    @Autowired
    private ImageMapper imageMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 修改用户头像
     */
    @Override
    @SneakyThrows
    public void changeImage(User user) {
        //照片地址
        String uploadFilePath = user.getImage();
        //调用第三方服务类，将照片转码为base64
        File imgFile = new File(uploadFilePath);//待处理的图片地址

        //此方法将图片转为base64出现bug 结果全为AAA
//        String imageBase64 = Base64.encodeBase64String(fileToByte(imgFile));

        String imageBase64 = ImageToBase64(uploadFilePath);
        //查看图片表是否有该数据流
        int image_id;
        Image image = imageMapper.selectOne(new LambdaQueryWrapper<Image>().in(Image::getImage, imageBase64));
        if (image == null) {
            //数据库中不存在此图片，向表格中添加照片数据流
            image = new Image();
            image.setImage(imageBase64);
            imageMapper.insertImage(image);
            image_id = image.getId();
            //获取Id
        } else {
            //存在照片,获取ID
            image_id = image.getId();
        }
        //删除生成的图片
//        imgFile.delete();
        userMapper.updateImage(user.getAccount(), image_id);
    }

    /**
     * 文件File类型转byte[]
     */
    @SneakyThrows
    public static byte[] fileToByte(File file) {
        return new byte[(int) file.length()];
    }

    /**
     * 本地图片转换Base64的方法
     */
    public static String ImageToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        return encoder.encode(Objects.requireNonNull(data));
    }
}
